package com.speedchina.framework.validator;

import com.speedchina.framework.exception.AssertException;
import com.speedchina.framework.exception.BException;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * 校验帮助（工具）类
 *
 * @author hank
 * @create 2017-03-15 上午10:50
 **/

public class ValidatorHelper {
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     *
     * @param object 待校验对象
     * @param groups 待校验的组
     * @throws BException 校验不通过，则报RRException异常
     */
    public static void validateEntity(Object object, Class<?>... groups)
            throws BException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
            int tempIndex = 0;
            StringBuilder msg = new StringBuilder();
            for (ConstraintViolation<Object> constraint : constraintViolations) {
                if (tempIndex > 0) {
                    msg.append("<br/>");
                }
                msg.append(constraint.getMessage());
                tempIndex++;
            }
            throw new BException(msg.toString());
        }
    }
}
